<template>
  <div id="xterm" class="xterm" />
</template>

<script>
import Vue from 'vue'
import store from '@/store/'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import 'xterm/css/xterm.css'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { AttachAddon } from 'xterm-addon-attach'

export default {
  name: 'Xterm',
  props: {
    socketURI: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      term: null,
      websock: null,
    }
  },
  mounted() {
    this.initWebSocket()
  },
  computed: {},
  activated() {
    this.initWebSocket()
  },
  deactivated() {
    // 离开页面生命周期函数
    console.log('WebSocket关闭')
    this.websock && this.websock.close()
    this.websock && this.term.dispose()
  },
  destroyed() {},
  methods: {
    initTerm() {
      const term = new Terminal({
        fontSize: 14,
        cursorBlink: true,
      })
      const attachAddon = new AttachAddon(this.websock)
      const fitAddon = new FitAddon()
      term.loadAddon(attachAddon)
      term.loadAddon(fitAddon)
      term.open(document.getElementById('xterm'))
      fitAddon.fit()
      term.focus()
      this.term = term
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id
      var url = ''
      if (process.env.NODE_ENV === 'production') {
        url = `ws://${window.location.host}/jeecg-boot/websocket/connectDevice/1/1`
      } else {
        url = `ws://192.168.1.142:9200/jeecg-boot/websocket/connectDevice/1/1`
        // var url = 'ws://' + ip + '/jeecg-boot/websocket/connectDevice/1/1' 
      }
      //update-begin-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      let token = Vue.ls.get(ACCESS_TOKEN)

      this.websock = new WebSocket(url, [token])
      //update-end-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
    },
    websocketOnopen: function () {
      console.log('WebSocket连接成功')
      this.initTerm()
    },
    websocketOnerror: function (e) {
      console.log('WebSocket连接发生错误')
    },
  },
}
</script>

<style lang="less" scoped>
.xterm {
  height: 100% !important;
}

::v-deep {
  .xterm {
    height: 100% !important;
  }

  .xterm-screen {
    height: 100% !important;
    width: 100% !important;
  }

  .xterm-rows {
    height: 100% !important;
  }
}
</style>
